package com.cloud.wx.share;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cloud.redis.config.RedisUtils;
import com.cloud.wx.model.response.WeixinShareResponse;
import lombok.AllArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Formatter;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@AllArgsConstructor
@Service
public class WeixinShareUtil {
    @Autowired
    RedisUtils redisUtils;

    /**
     * appid:微信appid
     * secret:微信secret
     * access_token:初始化access_token
     * shareUrl:分享的那个页面地址
     */
    public WeixinShareResponse shareSignature(String appid, String secret, String shareUrl) {
        String key = "cp:shareSignature";
        // 初始化access_token
        String access_token = "";

        Object o = redisUtils.get(key);
        String s = "";
        if (o != null) {
            s = Convert.toStr(o);
            if (s.contains("errcode")){
                s = getToken(appid, secret);
            }
        } else {
            s = getToken(appid, secret);
            redisUtils.set(key, s, 1, TimeUnit.HOURS);
        }
        JSONObject jsonObjectToken = null;
        try {
            jsonObjectToken = JSONUtil.parseObj(s);
        } catch (Exception e) {
            e.printStackTrace();
            //删除redis后再重试一次
            redisUtils.deleteKey(key);
            s = getToken(appid, secret);
            jsonObjectToken = JSONUtil.parseObj(s);
        }
        if (jsonObjectToken != null) {
            // 创建日期赋值为当前日期
//            long createDate = new Date().getTime() / 1000;
            // 获取Token值
            access_token = Convert.toStr(jsonObjectToken.get("access_token"));
            // 获取Token有效期值
//            long expires_in = Convert.toLong(jsonObjectToken.get("expires_in"));
        }

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&amp;type=jsapi";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", access_token);
        // 获取凭证
        String s1 = HttpUtil.get(requestUrl);
        JSONObject jsonObject = JSONUtil.parseObj(s1);
        if (jsonObject != null) {
            try {
                String ticket = jsonObject.getStr("ticket");
                String noncestr = create_nonce_str();
                String timestamp = create_timestamp();
                String param = "jsapi_ticket=" + ticket +
                        "&noncestr=" + noncestr +
                        "&timestamp=" + timestamp +
                        "&url=" + shareUrl;
                String signature = "";
                try {
                    MessageDigest crypt = MessageDigest.getInstance("SHA-1");
                    crypt.reset();
                    crypt.update(param.getBytes("UTF-8"));
                    signature = byteToHex(crypt.digest());
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                WeixinShareResponse weixinShareResponse = new WeixinShareResponse();
                weixinShareResponse.setWxNoncestr(noncestr);
                weixinShareResponse.setWxTimestamp(timestamp);
                weixinShareResponse.setWxSignature(signature);
                weixinShareResponse.setAppId(appid);
                weixinShareResponse.setWxUrl(shareUrl);
                String logData = JSONUtil.toJsonStr(weixinShareResponse);
                System.out.print("logData:" + logData + "，jsapi_ticket:" + ticket);
                return weixinShareResponse;
            } catch (Exception e) {
                redisUtils.deleteKey(key);
                e.printStackTrace();
            }
        }
        return null;
    }

    private String getToken(String appid, String secret) {
        String s;// 创建通过Api获取Token的链接与参数,需要增加7200秒
        String requestTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&amp;appid=APPID&amp;secret=SECRET";
        requestTokenUrl = requestTokenUrl.replace("APPID", appid);
        requestTokenUrl = requestTokenUrl.replace("SECRET", secret);
        s = HttpUtil.get(requestTokenUrl);
        return s;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
